package com.banksoft.front.controller;

import com.alibaba.fastjson.JSON;
import com.banksoft.admin.SystemCache;
import com.banksoft.admin.bean.CityBean;
import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.OrderService;
import com.banksoft.admin.service.UserService;
import com.banksoft.common.BaseController;
import com.banksoft.front.bean.Page;
import com.banksoft.front.bean.UserBean;
import com.banksoft.front.bean.UserTypeCompare;
import com.banksoft.util.CityUtil;
import com.banksoft.util.DateUtil;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by vanjoger on 2017/1/12.
 */
@Controller
@RequestMapping("/front/user/team")
public class FrontTeamController extends BaseController{

    @Autowired
    UserService userService;
    @Autowired
    BaseService baseService;
    @Autowired
    OrderService orderService;

    @RequestMapping("/list")
    public String list(String id, Model model, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
        boolean query = true;
        boolean level = false;
        if(!StringUtil.isNotNull(id)){
            id = user.getId();
            level = true;
        }else{
            query = dataPermission(id,user);
        }
        if(query) {
            List<UserBean> list = this.userService.listTeam(id,level);
            UserTypeCompare compare = new UserTypeCompare();
            Collections.sort(list,compare);
            model.addAttribute("list", list);
        }
        return "front/user_team_list";
    }

    private boolean dataPermission(String id, User user) {
        User up1 = this.baseService.findById(UserDao.class,id);
        if(up1!=null){
            if(up1.getId().equals(user.getId()))
                return true;
            User up2 = this.baseService.findById(UserDao.class,up1.getRecommendId());
            if(up2!=null){
                if(up2.getId().equals(user.getId()))
                    return true;
                User up3 = this.baseService.findById(UserDao.class,up2.getRecommendId());
                if(up3!=null){
                    if(up3.getId().equals(user.getId()))
                        return true;

                if(!user.getType().equals(MemberType.Customer.name())) {
                    User up4 = this.baseService.findById(UserDao.class, up3.getRecommendId());
                    if (up4 != null) {
                        if (up4.getId().equals(user.getId()))
                            return true;
                        User up5 = this.baseService.findById(UserDao.class,up4.getRecommendId());
                        if(up5!=null){
                            if(up5.getId().equals(user.getId()))
                                return true;
                            User up6 = this.baseService.findById(UserDao.class,up5.getRecommendId());
                            if(up6.getId().equals(user.getId()))
                                return true;
                        }
                    }
                }
              }
            }

        }
        return false;
    }

    @RequestMapping("/areaQuery")
    public String areaQuery(Model model,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);
        model.addAttribute("user",user);
        return "front/area_query";
    }

    @RequestMapping("/queryArea")
    @ResponseBody
    public JSONObject queryArea(String year,String month,String province,String city,String area,String userLevel){
        try{
            String nextYear = year;
            String startDate,endDate;
            if(month!=null&&!month.equals("")){
                int m = Integer.parseInt(month);
                if(m>11){
                    m = 1;
                    nextYear = (Integer.parseInt(year)+1)+"";
                }else{
                    m += 1;
                }
                String nextMonth = m+"";
                if(m<10)
                    nextMonth = "0"+m;
                startDate = year+"-"+month+"-01 00:00:00";
                endDate = nextYear+"-"+nextMonth+"-01 00:00:00";
            }else{
                nextYear = (Integer.parseInt(year)+1)+"";
                startDate = year+"-01-01 00:00:00";
                endDate = nextYear+"-01-01 00:00:00";
            }

            Map map = new HashMap();
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));

            map.put("province", province);
            map.put("city", city);
            map.put("area", area);

            map.put("status", new String[]{OrderStatus.Pay.name(),OrderStatus.Send.name(),OrderStatus.Suc.name()});

            List<Order> orderList = this.orderService.count(map);
            String totalMoney = "0";
            int gworder = 0;
            int sjorder = 0;
            if(StringUtil.isNotEmpty(orderList)){
                for(Order order:orderList){
                    if("0".equals(order.getType())){
                        gworder++;
                    }else if("1".equals(order.getType())){
                        sjorder++;
                    }
                    totalMoney = StringNumber.add(totalMoney,order.getTotalMoney());
                }
            }

            List<User> list = this.userService.list(map);
            int userTotal = list!=null?list.size():0;
            int userCnt = 0;
            int generalCnt = 0;
            int partnerCnt = 0;
            int goldCnt = 0;

            if(StringUtil.isNotEmpty(list)){
                for(User user:list){
                    if(user.getType().equals(MemberType.Gold.name())){
                        goldCnt ++;
                    }else if(user.getType().equals(MemberType.General.name())&&(!"1".equals(user.getIsPartner()))){
                        generalCnt++;
                    }else if(user.getType().equals(MemberType.General.name())&&("1".equals(user.getIsPartner()))){
                        partnerCnt++;
                    }else{
                        userCnt++;
                    }
                }
            }


            Map result = new HashMap();
            result.put("orderCnt",orderList!=null?orderList.size():0);
            result.put("totalMoney",totalMoney);
            result.put("gwOrder",gworder);
            result.put("sjOrder",sjorder);
            result.put("userCnt",userCnt);
            result.put("goldCnt",goldCnt);
            result.put("generalCnt",generalCnt);
            result.put("partnerCnt",partnerCnt);
            result.put("userTotal",userTotal);

            return this.FmtResult(true,null,result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }

    @RequestMapping("/userDetails")
    public String userDetails(String year,String month,String index,String province,String city,String area,Model model){
        model.addAttribute("year",year);
        model.addAttribute("month",month);
        model.addAttribute("index",index);
        model.addAttribute("province",province);
        model.addAttribute("city",city);
        model.addAttribute("area",area);
        return "front/area_query_details";
    }

    @RequestMapping("/queryUserDetails")
    @ResponseBody
    public JSONObject queryUserDetails(HttpServletRequest request,int pageNo,int pageSize,String year,String month,String index,String province,String city,String area){
        try{
            String nextYear = year;
            String startDate,endDate;
            if(month!=null&&!month.equals("")){
                int m = Integer.parseInt(month);
                if(m>11){
                    m = 1;
                    nextYear = (Integer.parseInt(year)+1)+"";
                }else{
                    m += 1;
                }
                String nextMonth = m+"";
                if(m<10)
                    nextMonth = "0"+m;
                startDate = year+"-"+month+"-01 00:00:00";
                endDate = nextYear+"-"+nextMonth+"-01 00:00:00";
            }else{
                nextYear = (Integer.parseInt(year)+1)+"";
                startDate = year+"-01-01 00:00:00";
                endDate = nextYear+"-01-01 00:00:00";
            }
            Map map = new HashMap();
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));
            map.put("province", province);
            map.put("city", city);
            map.put("area", area);
            if("1".equals(index)){
                map.put("type",MemberType.Customer.name());
            }else if("2".equals(index)){
                map.put("type",MemberType.Gold.name());
            }else if("3".equals(index)){
                map.put("type",MemberType.General.name());
                map.put("isPartner","0");
            }else if("4".equals(index)){
                map.put("type",MemberType.General.name());
                map.put("isPartner","1");
            }

            Page page = this.userService.queryPage(map,pageNo,pageSize);

            return this.FmtResult(true,null,page);
        }catch (Exception e){
            e.printStackTrace();
            return this.FmtResult(false,null,null);
        }
    }
}
